// 碳排类型占比/排行
var numberFormate = iot.getNumberFormat("0.00");

dev.action = function(resp,param){
    //获取工厂名称
    var factoryName = getFactoryName(param.workSpaceName);
    //是否算总还是单
    var totalOrSingle = param.selectType;
    if (totalOrSingle == null){
        totalOrSingle = "total";
    }
    var theTime = param.time;
    var timeSub = parseInt(theTime.substring(0,4));
    var workSpace = param.workSpace;
    var datas =  iot.list();
    var legend =  iot.list();
    var db = iot.db();

    var result = db.qry("SELECT es.type, SUM(win.dvalue) totalSum" +
        " FROM iot_dev_data_win win" +
        " LEFT JOIN energy_struc_prop esp ON win.dev_id = esp.dev_id AND esp.name = win.data_type" +
        " LEFT JOIN energy_struc es ON esp.energy_struc_id = es.id" +
        " WHERE es.name =" +
        " (SELECT name FROM energy_struc WHERE id = '" + workSpace + "')" +
        " AND win.the_time LIKE '" + theTime + "%'" +
        // " AND win.data_type like '%用量%'" +
        " GROUP BY es.type");
    //获取产量
    var yieldId = getFactoryYieldId(factoryName)

    var yieldResult = getFactoryYield(yieldId, theTime)

    var totalYield = yieldResult.totalSum;

    var dataType = ["电", "蒸汽", "水", "燃气"];
    var dataTypeCost = [
        carbonRowTimeModulus[factoryName] ? carbonRowTimeModulus[factoryName][timeSub].ele : 0, 0, 0,
        carbonRowTimeModulus[factoryName] ? carbonRowTimeModulus[factoryName][timeSub].gas : 0];
    var newResult = iot.list();
    // 去除dataType里面不存在的元素
    if (result) {
        result.forAll(function (item) {
            if (dataType.indexOf(item.type) > -1) {
                newResult.add({name: item.type, value: item.totalSum});
            }
        })
    }

    // 遍历结果集合，开始组装数据
    for (var i in dataType) {
        var data = 0;
        for (var key in newResult) {
            if (dataType[i].equals(newResult[key].name)) {
                data = newResult[key].value * dataTypeCost[i];
            }
        }

        //判断当前选择总数还是单车
        if (totalOrSingle.equals("total")) {
            datas.add({name: dataType[i], value: numberFormate.format(data)});
            legend.add(dataType[i]);
        }else if (totalOrSingle.equals("single")) {
            if (data && totalYield){
                data = data/totalYield;
            }
            legend.add(dataType[i]);
            datas.add({name: dataType[i], value: numberFormate.format(totalYield === null ? 0 : data)});
        }
    }
    var jsData = {
        datas : datas,
        legend : legend
    };
    resp.setJsData(jsData);
}